<template>
  <div class="container">
    <div ref="searchRef">
      <el-form
        :inline="true"
        :model="params"
        class="demo-form-inline grids gridColumns6"
      >
        <el-form-item
          :label="item.name"
          v-for="(item, index) in paramsList"
          :key="index"
        >
          <DatePicker
            @fatherMethods="search"
            v-model="params[item.field]"
            type="year"
            v-if="item.type == 'date'"
          ></DatePicker>
          <courseQuery
            @fatherMethods="search"
            multiple="1"
            v-model="params[item.field]"
            v-else-if="item.field == 'curriculum_id'"
          ></courseQuery>
          <tagSelect
            v-model="params[item.field]"
            multiple="1"
            v-else-if="item.field == 'tags'"
            @fatherMethods="search"
          ></tagSelect>
          <el-select
            v-model="params[item.field]"
            clearable
            :placeholder="`请选择${item.name}`"
            v-else-if="item.type == 'select'"
            @change="search"
          >
            <el-option
              v-for="(item, index) in item.options"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-input
            clearable
            type="number"
            @change="search"
            v-model="params[item.field]"
            :placeholder="`请输入${item.name}`"
            v-else-if="
              ['learningTime', 'totalLearningTime'].includes(item.field)
            "
          >
            <template #append>小时</template>
          </el-input>
          <el-input
            @change="search"
            clearable
            type="number"
            v-model="params[item.field]"
            :placeholder="`请输入${item.name}`"
            v-else-if="item.field == 'examScores'"
          >
            <template #append>分</template>
          </el-input>
          <div class="flex actionBtn" v-else-if="item.type == 'actionBtn'">
            <el-dropdown style="margin-right: 10px">
              <el-button type="primary">操作</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="search">查询</el-dropdown-item>
                  <el-dropdown-item
                    :disabled="!selectArr.length"
                    @click="
                      proxy.$refs.moxueyuanExportRef.open(params, selectData)
                    "
                    >学时信息导出</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="!selectArr.length"
                    @click="setPublished(1)"
                    >标记学时公布</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="!selectArr.length"
                    @click="setPublished(0)"
                    >撤销学时公布</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="!selectArr.length"
                    @click="handleBatch('0')"
                    >批量开启账号</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="!selectArr.length"
                    @click="handleBatch('1')"
                    >批量关闭账号</el-dropdown-item
                  >
                  <el-dropdown-item
                    :disabled="!selectArr.length"
                    @click="toDelete"
                    >转为历史记录</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button @click="init">重置</el-button>
          </div>
          <el-input
            @change="search"
            clearable
            v-model="params[item.field]"
            :placeholder="`请输入${item.name}`"
            v-else
          />
        </el-form-item>
      </el-form>
      <div style="margin-bottom: 10px" class="flex justifyBetween fz14">
        <div class="flex alignCenter">
          <div class="flex alignCenter">
            <el-icon color="#F56C6C" :size="20">
              <WarnTriangleFilled />
            </el-icon>
            代表报名课时与公布学时有差异
          </div>

          <div class="flex alignCenter" style="margin-left: 12px">
            <el-icon color="#409EFF" :size="20">
              <WarnTriangleFilled />
            </el-icon>
            代表该学员账号报名多门课程
          </div>
        </div>
        <div class="flex alignCenter">
          <el-text
            style="margin-right: 50px"
            class="mx-1"
            type="success"
            v-if="batchCurrent"
            >批量操作中：{{ batchCurrent }}/{{ selectArr.length }}</el-text
          >
          <el-text class="mx-1" type="primary"
            >数据最新更新时间:{{ newDataTime }}</el-text
          >
        </div>
      </div>
    </div>

    <el-table
      :element-loading-text="loadingText"
      :max-height="tableHeight"
      :data="tableData.rows"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column type="index" />
      <el-table-column prop="date" label="报名时间" width="160">
        <template #default="scope">
          {{ proxy.$utils.dateTimeFormateFn(scope.row._add_time, "all") }}
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="用户id" width="220" />
      <el-table-column prop="course_info.name" label="课程名称" width="500">
        <template #default="scope">
          <div class="flex alignCenter">
            {{ scope.row.course_info.name }}
            <div class="minus classStatus" v-if="scope.row.hasDiscount">减</div>
            <div class="gong classStatus" v-if="scope.row.isMoXueYuanPublished">
              公
            </div>
            <el-icon color="#F56C6C" :size="20" v-if="scope.row.published == 2">
              <WarnTriangleFilled />
            </el-icon>
            <el-icon color="#409EFF" :size="20" v-if="scope.row.isRepeat">
              <WarnTriangleFilled />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="user_detail_info.name" label="学员姓名">
        <template #default="scope">
          {{ scope.row.user_detail_info.name || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="user_detail_info.mobile"
        label="联系方式"
        width="120"
      >
        <template #default="scope">
          {{ scope.row.user_detail_info.mobile || "-" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="approvalContent.model.identityCard"
        label="身份证号"
        width="170"
      />
      <el-table-column
        prop="address"
        label="课程标签"
        width="80"
        show-overflow-tooltip
      >
        <template #default="scope">
          <el-popover placement="right" :width="200" trigger="click">
            <template #reference>
              <div class="button">{{ setTags(scope.row).length }}</div>
            </template>
            <el-table :data="setTags(scope.row)">
              <el-table-column prop="tagname" label="标签名称" />
            </el-table>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column
        :label="`第${index + 1}天`"
        width="100"
        align="center"
        v-for="(item, index) in bindMax"
        :key="index"
      >
        <template #default="scope">
          <el-popover placement="right" :width="400" trigger="click">
            <template #reference>
              <el-button text>{{
                tagStatus_format(scope.row.tagsStatus, index, "statusName")
              }}</el-button>
            </template>
            <el-table
              :data="
                tagStatus_format(scope.row.tagsStatus, index, 'trainContent')
              "
            >
              <el-table-column width="300" prop="contentName" label="课程" />
              <el-table-column
                width="100"
                prop="learningStatusFormat"
                label="状态"
              />
            </el-table>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="培训完成状态" width="110" align="center">
        <template #default="scope">
          <div v-if="scope.row.trainCompleted" style="color: #67c23a">
            已完成
          </div>
          <div v-else style="color: #f56c6c">未完成</div>
        </template>
      </el-table-column>
      <el-table-column label="学时" width="100" align="center">
        <template #default="scope">
          {{ scope.row.trainTotal * 8 }}
        </template>
      </el-table-column>
      <el-table-column label="公布学时" width="100" align="center">
        <template #default="scope">
          {{
            scope.row.isMoXueYuanPublished
              ? scope.row.isMoXueYuanPublished.currentTrainTotal * 8
              : "-"
          }}
        </template>
      </el-table-column>
      <el-table-column label="考试分数">
        <template #default="scope">
          {{ score_format(scope.row.examUsers_info) }}
        </template>
      </el-table-column>
      <el-table-column prop="user_count_info.passExam" label="关联考试">
        <template #default="scope">
          <el-popover placement="right" :width="300" trigger="click">
            <template #reference>
              <div class="button">
                {{ score_format(scope.row.examUsers_info, "total") }}
              </div>
            </template>
            <el-table :data="scope.row.examUsers_info">
              <el-table-column prop="examName" label="考试名称" />
              <el-table-column prop="score" label="考试分数" width="80" />
            </el-table>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="学时公布时间" width="120" align="center">
        <template #default="scope">
          {{
            scope.row.isMoXueYuanPublished
              ? proxy.$utils.dateTimeFormateFn(
                  scope.row.isMoXueYuanPublished.nowTime
                )
              : "-"
          }}
        </template>
      </el-table-column>
      <el-table-column
        prop="out_trade_no"
        label="订单号"
        width="170"
        show-overflow-tooltip
      />
      <el-table-column
        prop="user_statistics_info.lastActiveTime"
        label="最后活跃时间"
        width="160"
      />

      <!-- 
      <el-table-column prop="user_count_info.learningTime" label="有效学时" width="130" />
      <el-table-column prop="user_statistics_info.totalLearningTime" label="累计学时" width="160" />
      
      -->

      <!-- <el-table-column prop="user_detail_info.role" label="学员类型" width="100">
        <template #default="scope">
          <div v-if="!proxy.$utils.isEmptyObject(scope.row.user_detail_info)">
            {{scope.row.user_detail_info.role=="admin"?'管理员':'普通成员'}}
          </div>
        </template>
      </el-table-column> -->
      <el-table-column
        prop="user_detail_info.addTime"
        label="创建时间"
        width="160"
      >
        <template #default="scope">
          {{
            proxy.$utils.dateTimeFormateFn(
              scope.row.user_detail_info.addTime * 1000,
              "all"
            )
          }}
        </template>
      </el-table-column>
      <el-table-column prop="address" label="账号状态" fixed="right">
        <template #default="scope">
          <div v-if="!proxy.$utils.isEmptyObject(scope.row.user_detail_info)">
            <el-tag
              type="success"
              v-if="scope.row.user_detail_info.disabled == 0"
              >开启</el-tag
            >
            <el-tag type="info" v-else>关闭</el-tag>
          </div>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" width="100" align="center" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)" type="primary" text :disabled="proxy.$utils.isEmptyObject(scope.row.user_detail_info)">
            {{scope.row.user_detail_info.disabled==0?"关闭":"开启"}}
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <Pagination
      v-if="tableData['total']"
      :total="tableData['total']"
      v-model:page="params.pageIndex"
      v-model:limit="params.pageSize"
      @pagination="getInfo"
    />

    <moxueyuanExport ref="moxueyuanExportRef"></moxueyuanExport>
  </div>
</template>

<script setup lang="ts">
import moxueyuanExport from "@/views/courseManage/components/moxueyuanExport.vue";
const { proxy } = getCurrentInstance();
import useCounterStore from "@/store/counter";
const counter = useCounterStore();

let params = ref({
  pageIndex: 1,
  pageSize: 50,
  year: proxy.$utils.dateTimeFormateFn(Date.now(), "year"),
  curriculum_id: "",
  userid: "",
  name: "",
  mobile: "",
  identityCard: "",
  role: "",
  disabled: "",
  examScores: null, //考试分数
  totalLearningTime: null, //累计时长
  passExam: null, //考试合格
  completedTrain: "", //完成培训项目
  isRepeat: "", //报课数量
});
let selectData = ref([]); //选中的数据
let paramsList = ref([
  { field: "year", name: "年份", type: "date" },
  { field: "curriculum_id", name: "课程名称", type: "select" },
  { field: "name", name: "姓名", type: "input" },
  { field: "mobile", name: "联系方式", type: "input" },
  { field: "identityCard", name: "身份证号", type: "input" },
  // {
  //   field: "role",
  //   name: "学员类型",
  //   type: "select",
  //   options: [
  //     { label: "管理员", value: "admin" },
  //     { label: "普通成员", value: "user" },
  //   ],
  // },
  // { field: "completedTrain", name: "完成培训项目", type: "input" },
  // { field: "learningTime", name: "有效学时≥", type: "input" },
  // { field: "totalLearningTime", name: "累计学时≥", type: "input" },
  // { field: "examScores", name: "考试分数≥", type: "input" },
  // { field: "passExam", name: "考试合格", type: "input" },
  {
    field: "disabled",
    name: "账号状态",
    type: "select",
    options: [
      { label: "开启", value: "0" },
      { label: "关闭", value: "1" },
    ],
  },
  // { field: "tags", name: "课程标签", type: "select" },
  { field: "userId", name: "用户Id", type: "input" },
  { field: "out_trade_no", name: "订单号", type: "input" },
  {
    field: "trainCompleted",
    name: "培训完成的状态",
    type: "select",
    options: [
      { label: "已完成", value: 1 },
      { label: "未完成", value: 0 },
    ],
  },
  {
    field: "isMoXueYuanPublished",
    name: "课时公布状态",
    type: "select",
    options: [
      { label: "公布", value: "1" },
      { label: "未公布", value: "2" },
    ],
  },
  {
    field: "isRepeat",
    name: "报课数量",
    type: "select",
    options: [
      { label: "单门", value: 0 },
      { label: "多门", value: 1 },
    ],
  },
  { type: "actionBtn" },
]);

let tableData = ref({});
let loading = ref(false);
let selectArr = ref([]); //选中的数据
let delData = ref([]); //删除的数据整理
let searchHeight = ref(0);
let bindMax = ref(0);
let trains = ref([]);
let newDataTime = ref(0);
let isBatchOperate = ref(false); //是否在批量操作
let batchCurrent = ref(0); //批量操作到第几个人了

let loadingText = computed(() => {
  if (isBatchOperate.value) {
    return `批量操作中...${batchCurrent.value}/${selectData.value.length}`;
  } else {
    return "正在加载中...";
  }
});

let tableHeight = computed(() => {
  let hei =
    window.innerHeight - 84 - counter.pageHeight - 55 - searchHeight.value;
  return `${hei}px`;
});

onMounted(() => {
  search();
  searchHeight.value = proxy.$refs.searchRef.offsetHeight;
  getMaxBind();
});

async function setPublished(num) {
  try {
    let resp = await proxy.$utils.confirmTips(
      `确定要${num == 0 ? "撤销" : "设为"}公布吗?`
    );
    if (!resp) return;
    console.log("设为公布", selectData.value);
    loading.value = true;
    isBatchOperate.value = true;
    switch (num) {
      case 0: //撤销公布
        for (let index = 0; index < selectData.value.length; index++) {
          const element = selectData.value[index];
          await proxy.$apis.moxueyuanInfo({
            type: "setPublishedNo",
            data: {
              out_trade_no: element.out_trade_no,
              orderId: element._id,
            },
          });
          batchCurrent.value++;
        }
        proxy.$utils.showToast("撤销公布成功");
        break;
      case 1: //设为公布
        for (let index = 0; index < selectData.value.length; index++) {
          const element = selectData.value[index];
          await proxy.$apis.moxueyuanInfo({
            type: "setPublished",
            data: {
              out_trade_no: element.out_trade_no,
              orderId: element._id,
              currentTrainTotal: element.trainTotal,
              nowTime: Date.now(),
            },
          });
          batchCurrent.value++;
        }
        proxy.$utils.showToast("设为公布成功");
        break;
      default:
        break;
    }
    getInfo();
  } catch (error) {
    console.log("打标报错", error);
  } finally {
    batchCurrent.value = 0;
    isBatchOperate.value = false;
    loading.value = false;
  }
}

async function updateMoxueyuanlatestTime() {
  let resp = await proxy.$apis.moxueyuanInfo({
    type: "updateMoxueyuanlatestTime",
    data: {},
  });
  newDataTime.value = proxy.$utils.dateTimeFormateFn(
    resp.dataUpdateTime,
    "all"
  );
  console.log("最新时间", newDataTime.value);
}

function tagStatus_format(arr, index, key) {
  if (!arr) return;
  let current = index + 1;
  let sub = proxy.$utils.findIndexByField(arr, "index", current);
  if (sub != -1) {
    return arr[sub][key] || (key == "trainContent" ? [] : "-");
  } else if (key == "statusName") {
    return "-";
  } else {
    return [];
  }
}

function setTags(item) {
  let tagList = item.user_detail_info.tagList || [];
  let tags = item.tags;
  let arr = [];
  tagList.forEach((element) => {
    if (tags.includes(element.id)) arr.push(element);
  });
  return arr;
}

async function getMaxBind() {
  bindMax.value = await proxy.$apis.trainList({ type: "bindIndexMax" });
}

function handleSelectionChange(e) {
  selectData.value = proxy.$utils.deepcopy(e);
  selectArr.value = [];
  delData.value = [];
  for (let index = 0; index < e.length; index++) {
    const element = e[index];
    selectArr.value.push(element.mobile);
    //删除数据处理
    // delData.value.push({
    //   //报名时间
    //   registrationTime: element._add_time,
    //   courseName: element.course_info.name, //课程名称
    //   studentName: element.user_detail_info.name, //学员姓名
    //   mobile: element.user_detail_info.mobile, //手机号
    //   identityCard: element.approvalContent.model.identityCard, //身份证号
    //   tagList: element.user_detail_info.tagList, //课程标签
    //   learningTime: element.user_count_info.learningTime, //有效学时
    //   totalLearningTime: element.user_statistics_info.totalLearningTime, //累计学时
    //   exam_scores: element.examUsers_info, //考试分数
    //   passExam: element.user_count_info.passExam, //考试合格
    //   lastActiveTime: element.user_statistics_info.lastActiveTime, //最后活跃时间
    //   role: element.user_detail_info.role, //学员类型
    //   addTime: element.user_detail_info.addTime, //创建时间
    //   disabled: element.user_detail_info.disabled, //账号状态
    //   out_trade_no: element.out_trade_no, //订单号
    // });
  }
}

async function search() {
  params.value.pageIndex = 1;
  await updateMoxueyuanlatestTime();
  getInfo();
}

function init() {
  params.value = {
    pageIndex: 1,
    pageSize: 50,
    year: proxy.$utils.dateTimeFormateFn(Date.now(), "year"),
    curriculum_id: "",
    userid: "",
    name: "",
    mobile: "",
    identityCard: "",
    role: "",
    disabled: "",
    examScores: null, //考试分数
    totalLearningTime: null, //累计时长
    passExam: null, //考试合格
    completedTrain: "", //完成培训项目
  };
  getInfo();
}

//删除账号
async function toDelete() {
  try {
    loading.value = true;
    let resp = await proxy.$utils.confirmTips("确定要删除所选账号吗?");
    if (!resp) return;
    await proxy.$apis.moxueyuanInfo({
      type: "delete",
      data: delData.value,
    });
    proxy.$utils.showToast("删除成功");
    getInfo();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

async function handleBatch(num) {
  try {
    let resp = await proxy.$utils.confirmTips(
      "确定要批量" + (num == "0" ? "开启" : "关闭") + "所选账号吗?"
    );
    if (!resp) return;
    loading.value = true;
    isBatchOperate.value = true;
    for (let index = 0; index < selectData.value.length; index++) {
      const element = selectData.value[index];
      let data = {
        mobile: element.mobile,
        disabled: num,
        userid: element.user_detail_info.userid,
      };
      await proxy.$apis.moxueyuanInfo({ type: "update", data });
      batchCurrent.value++;
    }
    proxy.$utils.showToast("操作成功");
    getInfo();
  } catch (error) {
    console.log("什么报错", error);
  } finally {
    batchCurrent.value = 0;
    isBatchOperate.value = false;
    loading.value = false;
  }
}

function score_format(e, type?) {
  if (e && e.length) {
    let amount = 0;
    let arr = [];
    e.forEach((element) => {
      // if (element.stateValue == 2) {}
      arr.push(element);
      amount += Number(element.score);
    });
    if (type && type == "total") {
      return arr.length;
    } else {
      return amount ? (amount / arr.length).toFixed(2) : 0;
    }
  }
  return 0;
}

async function getInfo() {
  try {
    loading.value = true;
    tableData.value = await proxy.$apis.moxueyuanInfo({
      type: "list",
      data: params.value,
    });
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

async function handleEdit(row) {
  let name = row.user_detail_info.name;
  let resp = await proxy.$utils.confirmTips(
    "确定要" +
      (row.user_detail_info.disabled == 0 ? "关闭" : "开启") +
      name +
      "账号吗?"
  );
  if (!resp) return;
  let obj = {
    userid: row.user_detail_info.userid,
    disabled: row.user_detail_info.disabled == 0 ? "1" : "0",
  };
  await proxy.$apis.moxueyuanInfo({
    type: "update",
    data: obj,
  });
  proxy.$utils.showToast("操作成功");
  getInfo();
}
</script>

<style lang="scss" scoped>
.container {
  margin: 20px;
  .classStatus {
    border-radius: 50%;
    margin-left: 5px;
    width: 18px;
    height: 18px;
    line-height: 18px;
    text-align: center;
    color: #97999e;
    border: 1px solid #97999e;
    cursor: pointer;
    font-size: 12px;
    font-weight: bold;
  }
  .minus {
    color: #f66604 !important;
    border: 1px solid #f66604 !important;
  }
  .gong {
    color: #409eff !important;
    border: 1px solid #409eff !important;
  }
}
</style>
